package unit12;

public class demo01 {
    public static void main(String[] args) {
        Cinema cinema = new Cinema();
        cinema.sellTickets();
    }
}

class TicketSeller {
    private int fiveNumber = 3;
    private int tenNumber = 0;
    private int twentyNumber = 0;

    public synchronized void sellTicket(int receiveMoney) {
        if (receiveMoney == 5) {
            fiveNumber++;
            System.out.println(Thread.currentThread().getName() +
                    "给我5元钱，这是您的1张入场卷");
        } else if (receiveMoney == 10) {
            while (fiveNumber < 1) {
                try {
                    System.out.println(Thread.currentThread().getName() + "靠边等");
                    wait();
                    System.out.println(Thread.currentThread().getName() + "结束等待");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fiveNumber--;
            tenNumber++;
            System.out.println(Thread.currentThread().getName() +
                    "给我10元钱,找您5元,这是您的1张入场卷");
        } else if (receiveMoney == 20) {
            while (fiveNumber < 1 || tenNumber < 1) {
                try {
                    System.out.println(Thread.currentThread().getName() + "靠边等");
                    wait();
                    System.out.println(Thread.currentThread().getName() + "结束等待");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fiveNumber--;
            tenNumber--;
            twentyNumber++;
            System.out.println(Thread.currentThread().getName() +
                    "给20元钱，找您一张5元和一张10元，这是您的1张入场卷");
        }
        notifyAll();
    }
}

class Cinema {
    private Thread zhang, sun, zhao;
    private TicketSeller seller;

    public Cinema() {
        seller = new TicketSeller();
        zhang = new Thread(new Runnable() {
            @Override
            public void run() {
                seller.sellTicket(20);
            }
        }, "张某");

        sun = new Thread(new Runnable() {
            @Override
            public void run() {
                seller.sellTicket(10);
            }
        }, "李某");

        zhao = new Thread(new Runnable() {
            @Override
            public void run() {
                seller.sellTicket(5);
            }
        }, "赵某");
    }

    public void sellTickets() {
        zhang.start();
        sun.start();
        zhao.start();
    }
}